<template>
  <a-row id="globalHeader" align="center" :wrap="false">
    <a-col flex="auto">
      <a-menu
        mode="horizontal"
        :selected-keys="selectedKeys"
        @menu-item-click="doMenuClick"
      >
        <a-menu-item
          key="0"
          :style="{ padding: 0, marginRight: '38px' }"
          disabled
        >
          <div class="title-bar">
            <img class="logo" src="../assets/qhhc-logo.png" />
            <div class="title">黄海OJ</div>
          </div>
        </a-menu-item>
        <a-menu-item v-for="item in visibleRoutes" :key="item.path">
          {{ item.name }}
        </a-menu-item>
        <a-menu-item key="/contests">竞赛</a-menu-item>
      </a-menu>
    </a-col>
    <a-col flex="200px">
      <div class="user-actions">
        <template v-if="store.state.user?.loginUser?.userName !== '未登录'">
          <a-dropdown trigger="hover">
            <a-button type="text">
              {{ store.state.user?.loginUser?.userName }}
              <icon-down />
            </a-button>
            <template #content>
              <a-doption v-if="isAdmin" @click="toAdmin">
                <icon-settings /> 管理后台
              </a-doption>
              <a-doption @click="toContest" v-if="isAdmin">
                <icon-trophy /> 竞赛管理
              </a-doption>
              <a-doption @click="handleLogout">
                <icon-export /> 退出登录
              </a-doption>
            </template>
          </a-dropdown>
        </template>
        <template v-else>
          <a-space>
            <a-button type="primary" @click="toLogin">
              <icon-import /> 登录
            </a-button>
            <a-button @click="toRegister"> <icon-user-add /> 注册 </a-button>
          </a-space>
        </template>
      </div>
    </a-col>
  </a-row>
</template>

<script setup lang="ts">
import { routes } from "../router/routes";
import { useRoute, useRouter } from "vue-router";
import { computed, ref } from "vue";
import { useStore } from "vuex";
import checkAccess from "@/access/checkAccess";
import ACCESS_ENUM from "@/access/accessEnum";
import { UserControllerService } from "../../generated";
import { Message } from "@arco-design/web-vue";

const router = useRouter();
const store = useStore();

// 展示在菜单的路由数组
const visibleRoutes = computed(() => {
  return routes.filter((item, index) => {
    if (item.meta?.hideInMenu) {
      return false;
    }
    // 根据权限过滤菜单
    if (
      !checkAccess(store.state.user.loginUser, item?.meta?.access as string)
    ) {
      return false;
    }
    return true;
  });
});

// 判断是否为管理员
const isAdmin = computed(() => {
  return store.state.user.loginUser?.userRole === ACCESS_ENUM.ADMIN;
});

// 默认主页
const selectedKeys = ref(["/"]);

// 路由跳转后，更新选中的菜单项
router.afterEach((to, from, failure) => {
  selectedKeys.value = [to.path];
});

// 跳转到登录页
const toLogin = () => {
  router.push("/user/login");
};

// 跳转到注册页
const toRegister = () => {
  router.push("/user/register");
};

// 跳转到管理后台
const toAdmin = () => {
  router.push("/admin/dashboard");
};

// 跳转到竞赛管理
const toContest = () => {
  router.push("/admin/contest/list");
};

// 处理退出登录
const handleLogout = async () => {
  try {
    const res = await UserControllerService.userLogoutUsingPost();
    if (res.code === 0) {
      Message.success("退出登录成功");
      // 退出后刷新用户状态并跳转到首页
      await store.dispatch("user/getLoginUser");
      router.push("/");
      // 添加页面刷新
      window.location.reload();
    }
  } catch (error) {
    Message.error("退出登录失败");
  }
};

const doMenuClick = (key: string) => {
  router.push({
    path: key,
  });
};
</script>

<style scoped>
.title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: #444;
  margin-left: 16px;
}

.logo {
  height: 48px;
}

.user-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100%;
}
</style>
